<?php
/*新浪登录*/

namespace App\Lib;

class weibo
{
    private $conf;
    private $appKey;
    private $appSecret;
    protected $url = 'https://api.weibo.com';
    
    public function __construct()
    {
        $this->conf = config('thirdpart_login');
        $this->appKey = $this->conf['weibo']['appKey'];
        $this->appSecret = $this->conf['weibo']['appSecret'];
    }
    
    /**
     * @desc 运行
     * @param $accessToken
     * @return mixed
     * */
    public function run($accessToken)
    {
       $ret = self::getUserInfo($accessToken);
        if ($ret === false) {
            return false;
        }
        return $ret;
    }
    
    /**
     * @desc 获得用户详细信息
     * @param @accessToken
     * @return mixed
     * */
    public function getUserInfo($accessToken)
    {
        $tokenRet = self::getTokenInfo($accessToken);
        if(!$tokenRet){
            return false;
        }
        $uid = $tokenRet['uid'];
        $api = $this->url . "/2/users/show.json";
        $param = [
            'source' => $this->appKey,
            'access_token' => $accessToken,
            'uid' => $uid,
        ];
        
        $result = curl_request($api, $param, 'urlencoded', 'GET');
        $ret = json_decode($result,true);
        
        if(isset($ret['error_code'])){
            return false;
        }
        
        if($ret['gender'] == 'm'){
            $gender = 1;
        }elseif($ret['gender'] == 'f'){
            $gender = 2;
        }else{
            $gender = 3;
        }
        $location = explode(' ',$ret['location']);
        
        return [
            'unionid' => '',
            'openid' => (string)$ret['id'],
            'nickname' => $ret['screen_name'],
            'gender' => $gender,
            'province' => isset($location[0])?$location[0]:'',
            'city' => isset($location[1])?$location[1]:'',
            'portrait' => $ret['profile_image_url']
        ];
    }
    
    //获取token信息
    public function getTokenInfo($accessToken)
    {
        $api = $this->url . '/oauth2/get_token_info';
        $param = [
            'access_token' => $accessToken
        ];
        $result = curl_request($api, $param, 'urlencoded', 'POST');
        $ret = json_decode($result, true);
        if (isset($ret['error_code'])) {
            return false;
        }
        return $ret;
    }
    
}